package com.cinema.servlet.movie;

import com.cinema.dao.MovieDAO;
import com.cinema.entity.Movie;
import com.cinema.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 电影列表Servlet
 */
public class MovieListServlet extends HttpServlet {
    private MovieDAO movieDAO = new MovieDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查用户登录状态
        if (!checkLoginStatus(request, response)) {
            return;
        }

        String action = request.getParameter("action");

        if ("search".equals(action)) {
            handleSearch(request, response);
        } else {
            handleList(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * 检查用户登录状态
     */
    private boolean checkLoginStatus(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        HttpSession session = request.getSession(false);
        User user = null;

        if (session != null) {
            user = (User) session.getAttribute("user");
        }

        if (user == null) {
            System.out.println("用户未登录，重定向到登录页面");

            // 检查是否是AJAX请求
            String requestedWith = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestedWith)) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                String loginUrl = request.getContextPath() + "/login";
                response.getWriter().write("{\"success\": false, \"message\": \"登录已过期，请重新登录\", \"redirect\": \"" + loginUrl + "\"}");
                return false;
            }

            // 保存原始请求URL，登录后可以跳转回来
            String originalUrl = request.getRequestURI();
            String queryString = request.getQueryString();
            if (queryString != null) {
                originalUrl += "?" + queryString;
            }

            // 创建新session保存原始URL
            HttpSession newSession = request.getSession(true);
            newSession.setAttribute("originalUrl", originalUrl);

            // 重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }

        System.out.println("用户已登录: " + user.getUsername());
        return true;
    }

    /**
     * 处理电影列表显示
     */
    private void handleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            List<Movie> movies = movieDAO.findNowShowing();
            request.setAttribute("movies", movies);
            request.getRequestDispatcher("/movies.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取电影列表失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }

    /**
     * 处理电影搜索
     */
    private void handleSearch(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String title = request.getParameter("title");
        String genre = request.getParameter("genre");
        String city = request.getParameter("city");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String minPriceStr = request.getParameter("minPrice");
        String maxPriceStr = request.getParameter("maxPrice");

        Double minPrice = null;
        Double maxPrice = null;

        try {
            if (minPriceStr != null && !minPriceStr.trim().isEmpty()) {
                minPrice = Double.parseDouble(minPriceStr);
            }
            if (maxPriceStr != null && !maxPriceStr.trim().isEmpty()) {
                maxPrice = Double.parseDouble(maxPriceStr);
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "价格格式不正确");
        }

        try {
            List<Movie> movies = movieDAO.searchMovies(title, genre, city, startDate, endDate, minPrice, maxPrice);

            // 设置搜索条件回显
            request.setAttribute("searchTitle", title);
            request.setAttribute("searchGenre", genre);
            request.setAttribute("searchCity", city);
            request.setAttribute("searchStartDate", startDate);
            request.setAttribute("searchEndDate", endDate);
            request.setAttribute("searchMinPrice", minPriceStr);
            request.setAttribute("searchMaxPrice", maxPriceStr);

            request.setAttribute("movies", movies);
            request.setAttribute("isSearch", true);
            request.getRequestDispatcher("/movies.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "搜索电影失败");
            request.getRequestDispatcher("/movies.jsp").forward(request, response);
        }
    }
}
